<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>店铺管理</el-breadcrumb-item>
      <el-breadcrumb-item>商城模块</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入搜索商城模块名" v-model="queryInfo.query" clearable @clear="getmallmodeList">
            <el-button slot="append" icon="el-icon-search" @click="getmallmodeList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加商城模块</el-button>
        </el-col>
      </el-row>
      <el-table :data="mallmodeList" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="name" label="模块名称"></el-table-column>
        <el-table-column prop="image" label="模块图标">
          <template slot-scope="scope">
            <!-- 实现图片点击放大效果 -->
            <el-popover placement="top-start" trigger="hover">
              <img :src="scope.row.url" style="width: 150px; height: 150px" />
              <img :src="scope.row.url" slot="reference" style="width: 50px; height: 50px" />
            </el-popover>
          </template>          
        </el-table-column>
      <el-table-column align="center" label="跳转类型" prop="type">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == 0" type="success">小程序内部跳转</el-tag>
          <el-tag v-if="scope.row.type == 1">外部跳转</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="跳转链接" prop="link"/>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeadById(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="添加商城模块" :visible.sync="addDialogVisible" width="47%" :close-on-click-modal="false" @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="模块名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="模块图标" prop="image">
            <el-upload :action="uploadPath" :on-preview="handlePreview" :on-success='handleSuccess' :on-remove="handleRemove"  :file-list="fileList" :headers="headerObj" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="addForm.link"></el-input>
        </el-form-item>
        <el-form-item label="跳转类型" prop="type">
          <el-radio-group v-model="addForm.type">
            <el-radio :label="0">小程序内部跳转</el-radio>
            <el-radio :label="1">外部跳转</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addmallmode">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑商城模块" :visible.sync="editDialogVisible" width="30%" :close-on-click-modal="false" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="模块名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="模块图标">
            <el-upload :action="uploadPath" :on-preview="handlePreview" :on-success='handleEditSuccess' :on-remove="handleEditRemove" :file-list="fileList" :headers="headerObj" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="editForm.link"></el-input>
        </el-form-item>
        <el-form-item label="跳转类型" prop="type">
          <el-radio-group v-model="editForm.type">
            <el-radio :label="0">小程序内部跳转</el-radio>
            <el-radio :label="1">外部跳转</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editmallmode">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="图片预览" :visible.sync="previewVisible" width="80%" :close-on-click-modal="false">
      <img :src="previewPath" class="preview-img" />
    </el-dialog>
    
  </div>
</template>

<script>
import { basePath,uploadPath } from '../../../.env.development'
export default {
  data() {
    return {
      basePath,
      uploadPath,      
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      mallmodeList: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      adDialogVisible: false,
      previewVisible: false,
      options: [],
      previewPath: '',
      fileList: [],
      headerObj: {
        Authorization: JSON.parse(sessionStorage.getItem('userInfo')).token,
      },      
      addForm: {
        name: '',
        image: [],
        link: '',
        type: Number
      },
      editForm: {},
      addFormRules: {
        name: [
          { required: true, message: '请输入商城模块名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ]
      },
      editFormRules: {
        name: [
          { required: true, message: '请输入商城模块名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ]
      },
    }
  },
  created() {
    this.getmallmodeList()
  },
  methods: {
    async getmallmodeList() {
      const { data: res } = await this.$http.get('mallmode/', {
        params: this.queryInfo,
      })
      // if (res.meta.status !== 200) {
      //   return this.message.error('获取商城模块列表失败')
      // }
      const xx = JSON.parse(res.data)
      console.log('商城模块列表 xx', xx)
      xx.forEach(item =>{
        console.log('商城模块列表 item', item)
        this.$set(item,'url',basePath + item.image[0].pic)
      })
      this.mallmodeList = xx
      console.log('商城模块列表 res', this.mallmodeList)
      this.total = res.total
    },
    handlePreview(file) {
      this.previewVisible = true
      this.previewPath = file.url
      console.log('handlePreview file', file)
    },
    handleSuccess(response) {
      this.addForm.image.push({'pic':response.data.temp_path, pic_id:Math.floor(Math.random () * 9000)+1000})
      console.log('handleSuccess pics', this.addForm)
    },
    handleRemove(file) {
      const filePath = file.response.data.temp_path
      const i = this.addForm.image.findIndex(item => item.pic === filePath)
      console.log('handleRemove i',i)
      this.addForm.image.splice(i,1)
       console.log('handleRemove image',this.addForm.image)
    },
    handleEditSuccess(response) {
      this.editForm.image.push({'pic':response.data.temp_path, pic_id:Math.floor(Math.random () * 9000)+1000})
      console.log('handleEditSuccess pics', this.editForm)
    },
    handleEditRemove(file) {
      const filePath = file.temp_path || file.response.data.temp_path
      const i = this.editForm.image.findIndex(item => item.pic === filePath)
      console.log('handleEditRemove i',i)
      this.editForm.image.splice(i,1)
       console.log('handleEditRemove image',this.editForm.image)
    },         
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getmallmodeList()
    },
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getmallmodeList()
    },
    addDialogClose() {
      console.log('addDialogClose 111', this.fileList)
      this.$refs.addFormRef.resetFields()
    },
    editDialogClose() {
      this.fileList = []
      this.$refs.editFormRef.resetFields()
    },
    addmallmode() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        this.fileList = []
        const { data: res } = await this.$http.post('mallmode/', this.addForm)
        if(typeof(res) === 'string'){
            return this.$message.warning(res);
        }
        // if (res.meta.status !== 201) {
        //   return this.$message.error(res.meta.msg)
        // }
        this.addDialogVisible = false
        this.getmallmodeList()
        this.$message.success('添加商城模块成功')
      })
    },
    editmallmode() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`/mallmode/${this.editForm.id}/`, {
          name: this.editForm.name,
          image: this.editForm.image,
          link: this.editForm.link,
          type: this.editForm.type,
        })
        // if (res.meta.status !== 200) {
        //   return this.message.error('修改商城模块失败')
        // }
        if(typeof(res) === 'string'){
          return this.$message.warning(res)
        }           
        this.editDialogVisible = false
        this.getmallmodeList()
        this.$message.success('修改商城模块成功')
      })
    },
    async showEditDialog(id) {
      console.log('this.editForm.id', id)
      const { data: res } = await this.$http.get(`mallmode/${id}`)
      // if (res.meta.status !== 200) {
      //   return this.message.error('查询商城模块失败')
      // }
      console.log('mallmode edit res', res)
      if(res === '没有权限'){
        return this.$message.warning(res)
      }
      res.image.forEach(item => {
        this.fileList.push({
          name: item.pic_id,
          url: basePath + item.pic,
          temp_path: item.pic
          })
          
        })
      this.editForm = res
      this.editDialogVisible = true
    },
    removeadById(id) {
      this.$confirm('确定要删除该商城模块吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`mallmode/${id}`)
          console.log('ad delete res', typeof(res))
          // if (res.meta.status !== 200) {
          //   return this.message.error('删除商城模块失败')
          // }
          if(res === '没有权限'){
            return this.$message.warning(res)
          }          
          this.getmallmodeList()
          this.$message.success('删除商城模块成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    }
  },
}
</script>
<style lang="less" scoped>
.preview-img {
  width: 100%
}
.el-select .el-input{
    width: 581px;
  }
</style>
